package auto;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

/**
 * 原生Servlet中使用@WebServlet注册Servlet
 * @author libra
 */
@WebServlet(urlPatterns= {"/localLoad"})
//@WebInitParam()：进行paramInit初始化
//@WebFilter：注册Filter
//@WebListener：注册Listener
public class LocalLoadServlet extends HttpServlet {

	/**  */
	private static final long serialVersionUID = 4023442997406361930L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String flag = req.getParameter("flag");
		boolean isFlag = flag == null || flag.isBlank();
		/* 
		 * 创建FlowRule'流控规则'
		 */
	    FlowRule rule1 = new FlowRule();
	    // 定义'资源名'，限流规则的作用对象
	    rule1.setResource("GET:/hello");
	    // 定义'限流阈值'
	    rule1.setCount(0);
	    /*
	     * 定义'限流阈值'的类型
	     * 有RuleConstant.FLOW_GRADE_THREAD(线程数)、RuleConstant.FLOW_GRADE_QPS(QPS)两种
	     * 默认值为'QPS模式'
	     */
	    rule1.setGrade( RuleConstant.FLOW_GRADE_QPS );
	    // 指定'流控针对的调用来源'。默认值为'default'，代表不区分调用来源。
	    rule1.setLimitApp("default");
	    FlowRuleManager.loadRules( isFlag ? List.of() : List.of(rule1) );
	    
	    resp.setCharacterEncoding ("UTF-8"); 
	    resp.setContentType("text/html;charset=UTF-8");
		resp.getWriter().write(isFlag?"关闭QPS...":"开启QPS...");
	}
}